document.addEventListener('DOMContentLoaded', function () {
    const loginForm = document.getElementById('loginForm');
    const loginButton = document.getElementById('loginButton');
    const loginContainer = document.getElementById('loginContainer');

    // 配置后端API地址
    const API_BASE_URL = 'api/'; // 根据实际后端地址修改
    const LOGIN_ENDPOINT = `/login/${API_BASE_URL}`;

    // 表单提交处理
    loginForm.addEventListener('submit', async function (e) {
        e.preventDefault();

        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;
        const rememberMe = document.getElementById('rememberMe').checked;

        // 前端验证
        if (!username || !password) {
            showMessage('请填写所有必填字段', 'error');
            return;
        }

        if (password.length < 6) {
            showMessage('密码长度不能少于6位', 'error');
            return;
        }

        // 添加加载状态
        setLoadingState(true);

        try {
            // 调用后端登录接口
            const response = await fetch(LOGIN_ENDPOINT, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken'),
                },
                credentials: 'include',  // 关键，确保cookie被带上
                body: JSON.stringify({
                    username: username,
                    password: password,
                    remember_me: rememberMe
                })
            });

            const data = await response.json();
            console.log(data)
            if (response.ok && data.success) {
                // 登录成功
                showMessage('登录成功！正在跳转...', 'success');

                // 保存token或用户信息
                if (data.token) {
                    sessionStorage.setItem('auth_token', data.token);
                    if (rememberMe && data.refresh_token) {
                        localStorage.setItem('refresh_token', data.refresh_token);
                    }
                }

                // 保存用户信息
                if (data.user) {
                    sessionStorage.setItem('user_info', JSON.stringify(data.user));
                }

                // 延迟跳转到主页面
                setTimeout(() => {
                    window.location.href = data.redirect_url || '/index';
                }, 1500);

            } else {
                // 登录失败
                const errorMsg = data.message || data.error || '登录失败，请检查用户名和密码';
                showMessage(errorMsg, 'error');

                // 如果是密码错误，清空密码字段
                if (data.code === 'invalid_credentials') {
                    document.getElementById('password').value = '';
                    document.getElementById('password').focus();
                }
            }

        } catch (error) {
            console.log(data)
            console.error('登录请求失败:', error);

            if (error.name === 'TypeError' && error.message.includes('fetch')) {
                showMessage('网络连接失败，请检查网络后重试', 'error');
            } else {
                showMessage('登录服务暂时不可用，请稍后重试', 'error');
            }
        } finally {
            // 恢复按钮状态
            setLoadingState(false);
        }
    });

    // 设置加载状态
    function setLoadingState(isLoading) {
        if (isLoading) {
            loginContainer.classList.add('loading');
            loginButton.textContent = '登录中...';
            loginButton.disabled = true;
        } else {
            loginContainer.classList.remove('loading');
            loginButton.textContent = '登录';
            loginButton.disabled = false;
        }
    }

    // 显示消息提示
    function showMessage(message, type = 'info') {
        // 移除已存在的消息
        const existingMsg = document.querySelector('.message-toast');
        if (existingMsg) {
            existingMsg.remove();
        }

        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `message-toast ${type}`;
        messageEl.textContent = message;

        // 添加样式
        Object.assign(messageEl.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '12px 20px',
            borderRadius: '8px',
            color: 'white',
            fontSize: '14px',
            fontWeight: '500',
            zIndex: '10000',
            transform: 'translateX(100%)',
            transition: 'transform 0.3s ease',
            maxWidth: '300px',
            wordBreak: 'break-word'
        });

        // 设置背景色
        if (type === 'success') {
            messageEl.style.background = 'linear-gradient(135deg, #48bb78, #38a169)';
        } else if (type === 'error') {
            messageEl.style.background = 'linear-gradient(135deg, #f56565, #e53e3e)';
        } else {
            messageEl.style.background = 'linear-gradient(135deg, #667eea, #764ba2)';
        }

        // 添加到页面
        document.body.appendChild(messageEl);

        // 显示动画
        setTimeout(() => {
            messageEl.style.transform = 'translateX(0)';
        }, 100);

        // 自动隐藏
        setTimeout(() => {
            messageEl.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }, 3000);
    }

    // 获取CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 输入框焦点效果
    const inputs = document.querySelectorAll('.form-input');
    inputs.forEach(input => {
        input.addEventListener('focus', function () {
            this.parentElement.classList.add('focused');
        });

        input.addEventListener('blur', function () {
            this.parentElement.classList.remove('focused');
        });

        // 实时验证
        input.addEventListener('input', function () {
            if (this.value.trim()) {
                this.style.borderColor = '#667eea';
            } else {
                this.style.borderColor = '#e2e8f0';
            }
        });
    });

    // 回车键快捷登录
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            const focusedElement = document.activeElement;
            if (focusedElement.classList.contains('form-input')) {
                e.preventDefault();
                loginForm.dispatchEvent(new Event('submit'));
            }
        }
    });

    // 忘记密码处理
    const forgotPasswordLink = document.querySelector('.forgot-password');
    forgotPasswordLink.addEventListener('click', function (e) {
        e.preventDefault();
        showMessage('请联系管理员重置密码', 'info');
        // 实际项目中可以跳转到忘记密码页面
        // window.location.href = '/forgot-password/';
    });

    // 注册链接处理
    const registerLink = document.querySelector('.register-link a');
    registerLink.addEventListener('click', function (e) {
        e.preventDefault();
        // 实际项目中可以跳转到注册页面
        window.location.href = '/register/';
    });

    // 检查是否已登录
    const authToken = sessionStorage.getItem('auth_token');
    console.log(authToken)
    if (authToken) {
        // 验证token是否有效
        fetch(`/login/verify-token/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`,
                'X-CSRFToken': getCookie('csrftoken'),
            },
            credentials: 'include'
        })
            .then(response => response.json())
            .then(data => {
                if (data.valid) {
                    // Token有效，直接跳转
                    window.location.href = '/index/';
                } else {
                    // Token无效，清除存储
                    sessionStorage.removeItem('auth_token');
                    sessionStorage.removeItem('user_info');
                }
            })
            .catch(error => {
                console.log('Token验证失败:', error);
            });
    }
});
